// index.js
const app = getApp();
Page({
  data: {
    content: '',
    // 当前登录者信息
    login: {},
    // 聊天信息
    chatList: [],
  },
  // 输入监听
  inputClick(e) {
    this.setData({
      content: e.detail.value
    })
  },
  // 发送监听
  sendClick() {
    var that = this;
    var list = this.data.chatList;
    // 获取当前时间
    var date = new Date();
    var time = date.getTime();//获取时间戳
    console.log(date)
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minu = date.getMinutes();
    var now1 = month < 10 ? '0' + month : month;
    var now2 = day < 10 ? '0' + day : day;
    var toUid = this.data.login.toUID;
    // 组装数据
    var msg = {
      msgId: this.data.login.id,
      nickname: this.data.login.user,
      avatar: this.data.login.avatar,
      message: this.data.content,
      type: 'text',
      date: now1 + '-' + now2 + ' ' + hour + ':' + minu
    }
    //发送websocket
    const inputMessage = '{"message": "' + msg.message + '", "toUID": "' + toUid + '", "time":"' + time + '"}';
    // 发送消息
    wx.sendSocketMessage({
      data: inputMessage,
    })
    console.log(msg);
    this.setData({
      chatList: list.concat(msg)
    }, () => {
      that.scrollToBottom();
      that.setData({
        content: ''
      })
    })
  },
  // 滑动到最底部
  scrollToBottom() {
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 200000,
        duration: 3
      });
    }, 600)
  },

  // 页面加载时建立WebSocket连接
  onLoad: function (options) {
    //获取组装数据
    this.getChatData(options);
    this.scrollToBottom();
    this.connectWebSocket(options);

  },

  getChatData: function (options) {
    const fromUID = app.globalData.userId;
    const toUID = options.userId;
    // 发送 POST 请求
    wx.request({
      url: app.globalData.url + '/getChatList/' + fromUID, // 你的接口地址
      method: 'POST',
      data: {
        toUID: toUID
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      }, success: (res) => {
        // 请求成功时的回调
        console.log('请求成功', res.data);
        var dataItem = res.data.data;
        var login = {
          id: dataItem.fromUser.uidStr,
          user: dataItem.fromUser.name,
          avatar: dataItem.fromUser.avatar,
          toUID: dataItem.toUser.uidStr
        }
        var chatList = [];
        for (let i = 0; i < dataItem.chatsList.length; i++) {
          var nickname = dataItem.chatsList[i].senderUidStr == login.id ? dataItem.fromUser.name : dataItem.toUser.name;
          var avatar = dataItem.chatsList[i].senderUidStr == login.id ? dataItem.fromUser.avatar : dataItem.toUser.avatar
          var item = {
            msgId: dataItem.chatsList[i].senderUidStr,
            nickname: nickname,
            avatar: avatar,
            message: dataItem.chatsList[i].messageText,
            type: 'text',
            date: dataItem.chatsList[i].sendTime
          }
          chatList.push(item);
        }
        this.setData({
          login: login,
          chatList: chatList
        });

      },
      fail: (err) => {
        // 请求失败时的回调
        console.error('请求失败', err);
      }
    });
  },

  // 建立WebSocket连接
  connectWebSocket: function (options) {
    const fromUID = app.globalData.userId;
    const toUID = options.userId;
    const socketTask = wx.connectSocket({
      url: app.globalData.wsUrl + '/server/' + fromUID, // 替换成你的后端WebSocket地址
    });

    // 监听WebSocket连接打开事件
    socketTask.onOpen(() => {
      console.log('WebSocket连接已打开');
    });

    // 监听WebSocket接收到服务器的消息事件
    socketTask.onMessage((res) => {
      console.log('收到消息:', res.data);
      var message = JSON.parse(res.data);
      var chatList = this.data.chatList;
      //获取发送人的信息
      wx.request({
        url: app.globalData.url+'/users/getUserById/' + message.fromUID, // 你的接口地址
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        }, success: (res) => {
          console.log(res.data);
          var dataOne = res.data.data;
          // 更新页面上的消息列表
          var nickname = dataOne.name;
          var avatar = dataOne.avatar;
          console.log(avatar);
          var item = {
            msgId: dataOne.uidStr,
            nickname: nickname,
            avatar: avatar,
            message: message.message,
            type: 'text',
            date: message.time
          }
          chatList.push(item);
          this.setData({
            chatList: chatList
          })
        },
        fail: (err) => {
          // 请求失败时的回调
          console.error('请求失败', err);
        }
      });

    });

    // 监听WebSocket连接关闭事件
    socketTask.onClose((res) => {
      console.log('WebSocket连接已关闭:', res);
    });

    // 监听WebSocket错误事件
    socketTask.onError((res) => {
      console.error('WebSocket连接发生错误:', res);
    });
  },

  //跳转到tabBar页面  
  gotoPage: function (options) {
    wx.navigateTo({
      url: '/pages/createskillpage/index',
      success: function (res) {
        // 跳转成功后的回调
      },
      fail: function (res) {
        // 跳转失败的回调
        console.log(res);
      }
    })
  },
});
